<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" append-to-body width="70%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row>
        <!-- <el-col :span="8">
          <el-form-item label="流程实例编号" prop="processInstanceId">
            <el-input v-model="formData.processInstanceId" placeholder="请输入流程实例的编号" />
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="续签合同序号" prop="parentId">
            <el-select v-model="formData.parentId" clearable placeholder="请选择续签合同序号">
              <el-option
                v-for="item in historyList"
                :key="item.id"
                :value="item.id"
                :label="item.contractNo"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="有效状态" prop="effective">
            <el-select v-model="formData.effective" placeholder="请选择有效状态">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.SYS_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="填报人ID" prop="proposerId">
            <el-input v-model="formData.proposerId" placeholder="请输入填报人ID" />
          </el-form-item>
        </el-col> -->
        <el-col :span="6">
          <el-form-item label="租赁宗地序号" prop="landIds">
            <el-input v-model="formData.landIds" clearable placeholder="请选择宗地" />
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="openChooseLand">选择</el-button>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属用户" prop="userId">
            <el-select
              v-model="formData.userId"
              clearable
              filterable
              @focus="getUserList()"
              placeholder="请输入所属用户ID"
              class="!w-240px"
            >
              <el-option
                v-for="user in userList"
                :key="user.id"
                :label="user.nickname"
                :value="user.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合同编号" prop="contractNo">
            <el-input v-model="formData.contractNo" placeholder="请输入合同编号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="出租金额" prop="rentPrice">
            <el-input v-model="formData.rentPrice" placeholder="请输入出租金额" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="出租期限" prop="rentPeriod">
            <el-input v-model="formData.rentPeriod" placeholder="请输入出租期限" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              v-model="formData.startTime"
              type="date"
              value-format="x"
              placeholder="选择开始时间"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
              v-model="formData.endTime"
              type="date"
              value-format="x"
              placeholder="选择结束时间"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="出租位置" prop="rentLocation">
            <el-input v-model="formData.rentLocation" placeholder="请输入出租位置" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="租赁土地面积" prop="rentLandarea">
            <el-input v-model="formData.rentLandarea" placeholder="请输入租赁土地面积" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="租赁建筑面积" prop="rentBuildingarea">
            <el-input v-model="formData.rentBuildingarea" placeholder="请输入租赁建筑面积" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="出租方式" prop="rentType">
            <el-select v-model="formData.rentType" placeholder="请选择出租方式">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.RENT_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合同签订日期" prop="signingDate">
            <el-date-picker
              v-model="formData.signingDate"
              type="date"
              value-format="x"
              placeholder="选择合同签订日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="约定交款日期" prop="payDate">
            <el-date-picker
              v-model="formData.payDate"
              type="date"
              value-format="x"
              placeholder="选择约定交款日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="上次交款日期" prop="paidDate">
            <el-date-picker
              v-model="formData.paidDate"
              type="date"
              value-format="x"
              placeholder="选择上次交款日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="下次交款日期" prop="nextpayDate">
            <el-date-picker
              v-model="formData.nextpayDate"
              type="date"
              value-format="x"
              placeholder="选择下次交款日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 子表的表单 -->
    <el-tabs v-model="subTabsName">
      <el-tab-pane label="租赁合同档案" name="rentFile">
        <RentFileForm ref="rentFileFormRef" :belong-id="formData.id" />
      </el-tab-pane>
      <el-tab-pane label="宗地信息" name="land">
        <LandForm ref="landFormRef" :land-ids="formData.landIds" />
      </el-tab-pane>
      <el-tab-pane label="年度收益" name="earnings">
        <EarningsForm ref="earningsFormRef" :rent-id="formData.id" />
      </el-tab-pane>
      <el-tab-pane label="承租人信息" name="lessee">
        <LesseeForm ref="lesseeFormRef" :rent-id="formData.id" />
      </el-tab-pane>
      <el-tab-pane label="租金税费管理" name="taxation">
        <TaxationForm ref="taxationFormRef" :rent-id="formData.id" />
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <el-button
        @click="submitForm"
        type="primary"
        :disabled="formLoading"
        v-hasPermi="['zszx:rent:update']"
        >确 定</el-button
      >
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
    <!-- <LandForm ref="landFormRef" @success="getList" /> -->
  </Dialog>
  <el-dialog title="选择宗地" v-model="chooseLanDialogVisible" append-to-body width="70%">
    <ChooseLand ref="chooseLandRef" @land-selected="ChooseLandOK" />
  </el-dialog>
</template>
<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { RentApi, RentVO } from '@/api/zszx/rent'
import LesseeForm from './components/LesseeForm.vue'
import TaxationForm from './components/TaxationForm.vue'
import EarningsForm from './components/EarningsForm.vue'
import LandForm from './components/LandForm.vue'
import RentFileForm from './components/RentFileForm.vue'

import ChooseLand from '@/views/zszx/land/ChooseLand.vue'
import { useUserStore } from '@/store/modules/user'

const chooseLanDialogVisible = ref(false)

// import { LandApi, LandVO } from '@/api/zszx/land'

// /** 添加/修改操作 */
// const landFormRef = ref()
// const openLandForm = (type: string, id?: number) => {
//   landFormRef.value.open(type, id)
// }

/** 选择土地 */
const chooseLandRef = ref()
const openChooseLand = () => {
  chooseLanDialogVisible.value = true
}
function ChooseLandOK(data) {
  // console.log(data, data.id)
  if (formData.value.landIds) {
    const ids = new Set(formData.value.landIds.split(',')) // 拆分为数组并去重
    ids.add(data.id.toString()) // 添加新 ID（自动去重）
    formData.value.landIds = Array.from(ids).join(',') // 重新拼接为字符串
  } else {
    formData.value.landIds = data.id.toString() //统一为字符串
  }
  chooseLanDialogVisible.value = false
}

import * as UserApi from '@/api/system/user'
const userList = ref<UserApi.UserVO[]>([]) // 用户列表
async function getUserList() {
  userList.value = await UserApi.getSimpleUserList()
}

/** 租赁合同管理 表单 */
defineOptions({ name: 'RentForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const userStore = useUserStore()

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  processInstanceId: undefined,
  proposerId: undefined,
  parentId: undefined,
  effective: undefined,
  status: undefined,
  landIds: '',
  userId: undefined,
  contractNo: undefined,
  rentPrice: undefined,
  rentPeriod: undefined,
  startTime: undefined,
  endTime: undefined,
  rentLocation: undefined,
  rentLandarea: undefined,
  rentBuildingarea: undefined,
  rentType: undefined,
  signingDate: undefined,
  payDate: undefined,
  paidDate: undefined,
  nextpayDate: undefined,
  remark: undefined
})
const formRules = reactive({
  landIds: [{ required: true, message: '租赁宗地序号不能为空', trigger: 'blur' }],
  contractNo: [{ required: true, message: '合同编号不能为空', trigger: 'blur' }],
  payDate: [{ required: true, message: '约定交款日期不能为空', trigger: 'blur' }],
  rentPrice: [{ required: true, message: '出租金额不能为空', trigger: 'blur' }],
  startTime: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
  endTime: [{ required: true, message: '结束时间不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 子表的表单 */
const subTabsName = ref('rentFile')
const lesseeFormRef = ref()
const taxationFormRef = ref()
const earningsFormRef = ref()
const landFormRef = ref()
const rentFileFormRef = ref()

const historyList = ref([])

/** 打开弹窗 */
const open = async (type: string, id?: number, row?: RentVO) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await RentApi.getRent(id)
    } finally {
      formLoading.value = false
    }
  } else {
    // 创建时，设置续签ID
    if (row) {
      formData.value = {
        id: undefined,
        processInstanceId: undefined,
        proposerId: userStore.getUser.id,
        parentId: row?.id,
        effective: undefined,
        status: undefined,
        landIds: row.landIds,
        userId: row.userId,
        contractNo: row.contractNo,
        rentPrice: row.rentPrice,
        rentPeriod: row.rentPeriod,
        startTime: undefined,
        endTime: undefined,
        rentLocation: row.rentLocation,
        rentLandarea: row.rentLandarea,
        rentBuildingarea: row.rentBuildingarea,
        rentType: row.rentType,
        signingDate: undefined,
        payDate: undefined,
        paidDate: undefined,
        nextpayDate: undefined,
        remark: undefined
      }
      // formData.value.parentId = row?.id
    }
    historyList.value = await RentApi.historyList()
    // console.log('historyList', historyList.value)
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 校验子表单
  try {
    await rentFileFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'rentFile'
    return
  }
  try {
    await landFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'land'
    return
  }
  try {
    await lesseeFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'lessee'
    return
  }
  try {
    await taxationFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'taxation'
    return
  }
  try {
    await earningsFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'earnings'
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as RentVO
    // 拼接子表的数据
    data.lands = landFormRef.value.getData()
    data.rentFiles = rentFileFormRef.value.getData()
    data.lessees = lesseeFormRef.value.getData()
    data.taxations = taxationFormRef.value.getData()
    data.earningss = earningsFormRef.value.getData()
    if (formType.value === 'create') {
      await RentApi.createRent(data)
      message.success(t('common.createSuccess'))
    } else {
      await RentApi.updateRent(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    processInstanceId: undefined,
    parentId: undefined,
    effective: undefined,
    status: undefined,
    proposerId: undefined,
    landIds: '',
    userId: undefined,
    contractNo: undefined,
    rentPrice: undefined,
    rentPeriod: undefined,
    startTime: undefined,
    endTime: undefined,
    rentLocation: undefined,
    rentLandarea: undefined,
    rentBuildingarea: undefined,
    rentType: undefined,
    signingDate: undefined,
    payDate: undefined,
    paidDate: undefined,
    nextpayDate: undefined,
    remark: undefined
  }
  formRef.value?.resetFields()
}
</script>
